﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Otgruzka.ServicesClients;
using BusinessLogic.Statuses;
using BusinessLogic;
using BusinessLogic.Security;
using DataTier.Entities;
using System.ServiceModel;

namespace Otgruzka.Controls.UserAccount
{
    public partial class JuridicalPersonEdit : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BingPromptMessages();
            if (!this.IsPostBack)
                BindData();
        }

        /// <summary>
        /// Отображение подсказок из БД
        /// </summary>
        private void BingPromptMessages()
        {
            try
            {
                string[] messages = new PromptMessagesClient().GetPromptMessages(this.AppRelativeVirtualPath.Substring(this.AppRelativeVirtualPath.LastIndexOf("/") + 1)).ToArray();

                if (messages != null && messages.Count() > 0)
                {
                    this.PromptMessagesRepeater.DataSource = messages;
                    this.PromptMessagesRepeater.DataBind();
                    this.PromptMessagesRepeater.Visible = true;
                }
                else
                {
                    this.PromptMessagesRepeater.Visible = false;
                }
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// Заполнение данными
        /// </summary>
        private void BindData()
        {
            this.NewIDCompany.DataSource = new DictionariesClient().GetCompanyList(UserPrincipal.Current.UserId);
            this.NewIDCompany.DataBind();

            this.Juridical.DataSource = new DictionariesClient().GetJuridicalPersonList(UserPrincipal.Current.UserId);
            this.Juridical.DataBind();

            //this.CompanyListID.DataSource = new DictionariesClient().GetJuridicalPersonList(UserPrincipal.Current.UserId);
        }

        /// <summary>
        /// Начала редактирование строки
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Juridical_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //Set the edit index.
            this.Juridical.EditIndex = e.NewEditIndex;

            //Bind data to the GridView control.
            BindData();
        }

        /// <summary>
        /// Обновление строки после редактирования
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Juridical_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            DropDownList drdList;
            drdList = (DropDownList)(Juridical.Rows[e.RowIndex].Cells[1].FindControl("NewCompanyID"));

            var client = new DictionariesClient();
            try
            {
                var jur = new JuridicalPersonEntity()
                {
                    Name = e.NewValues["Name"] != null ? e.NewValues["Name"].ToString() : "",
                    ManagerEMail = e.NewValues["ManagerEMail"] != null ? e.NewValues["ManagerEMail"].ToString() : "",
                    CompanyId = (drdList.SelectedItem != null) ? Convert.ToInt32(drdList.SelectedItem.Value) : (int?)null,
                    JuridicalPersonId = e.Keys["JuridicalPersonId"] != null ? Convert.ToInt32(e.Keys["JuridicalPersonId"]) : 0
                };
                client.SaveJuridicalPerson(UserPrincipal.Current.UserId, jur);
                Juridical.EditIndex = -1;
                BindData();
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
                e.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Отмена редактирования строки
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Juridical_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //Reset the edit index.
            Juridical.EditIndex = -1;

            //Bind data to the GridView control.
            BindData();
        }

        /// <summary>
        /// Обработка строк при заполнении GridView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Juridical_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var compID = e.Row.FindControl("NewCompanyID") as DropDownList;
                if (compID != null)
                {
                    compID.DataSource = new DictionariesClient().GetCompanyList(UserPrincipal.Current.UserId);
                    compID.DataBind();
                }
            }
        }



        protected void Juridical_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var client = new DictionariesClient();
            int juridicalPersonId = (int)e.Keys[0];
            try
            {
                client.DeleteJuridicalPerson(UserPrincipal.Current.UserId, juridicalPersonId);
                BindData();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
                e.Cancel = true;
                return;
            }
            catch (System.Exception exp)
            {
                //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Ошибка удаления : " + exp.Message + "');", true);

                //string message = string.Format("Ошибка удаления: <br />{0}", ExceptionHelper.GetAllMessage(exp));
                //this.ErrorMessage.Text = message;

                e.Cancel = true;
                return;
            }
            //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Товар успешно удален.');", true);
        }


        /// <summary>
        /// Кнопка сохранения нового юридического лица
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddNewJur_Click(object sender, EventArgs e)
        {
            //DropDownList drdList;
            //drdList = (DropDownList)(Juridical.Rows[e.RowIndex].Cells[1].FindControl("NewCompanyID"));

            string newNameJur = this.NewNameJur.Text;
            string newManagerEMailJur = this.NewManagerEMailJur.Text;
            
            int newIDCompany = (this.NewIDCompany.SelectedItem != null) ? Convert.ToInt32(this.NewIDCompany.SelectedItem.Value) : 0;
            
            if (newNameJur.Length>0 && newIDCompany!=0)
            {
                var client = new DictionariesClient();
                try
                {
                    var jur = new JuridicalPersonEntity()
                    {
                        Name = newNameJur,
                        ManagerEMail = newManagerEMailJur,
                        CompanyId = Convert.ToInt32(newIDCompany),
                    };
                    client.SaveJuridicalPerson(UserPrincipal.Current.UserId, jur);
                    BindData();
                    this.NewNameJur.Text = "";
                    this.NewManagerEMailJur.Text = "";
                }
                catch (System.Exception exp)
                {
                    this.ErrorMessage.Text = exp.Message;
                    return;
                }
            }
            else
            {
                this.ErrorMessage.Text = "Нельзя";
                return;
            }
        }

        protected void Juridical_RowDeleted(object sender, GridViewDeleteEventArgs e)
        {
            //var client = new DictionariesClient();
            //int juridicalID = (int)e.Keys[0];
            //try
            //{
            //    client.DeleteProduct(UserPrincipal.Current.UserId, productId);
            //}
            //catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            //{
            //    string message = client.GetExceptionDetail(ex);
            //    this.ErrorMessage.Text = message;
            //    e.Cancel = true;
            //    return;
            //}
            //catch (System.Exception exp)
            //{
            //    //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Ошибка удаления : " + exp.Message + "');", true);

            //    //string message = string.Format("Ошибка удаления: <br />{0}", ExceptionHelper.GetAllMessage(exp));
            //    //this.ErrorMessage.Text = message;

            //    e.Cancel = true;
            //    return;
            //}
            ////ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Товар успешно удален.');", true);
        }
    }
}